package com.jxtti.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.jxtti.entity.SiteContent;
import com.jxtti.entity.SiteMenu;
import com.jxtti.service.SiteContentService;
import com.jxtti.service.SiteMenuService;
import com.jxtti.utils.BaseCodec;
import com.jxtti.utils.ExceptionUtil;
import com.jxtti.utils.StringUtil;



@Controller
@RequestMapping("/SiteContent") 
public class SiteContentController {
	private final static Logger log= Logger.getLogger(SiteContentController.class);
	
	@Autowired //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private SiteContentService  SiteContentService; 
	
	@InitBinder  //初始化数据的时候，进行数据类型转换，String类型转为Date类型
    public void initBinder(WebDataBinder binder) {     
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");     
        dateFormat.setLenient(false);     
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));//true:���������ֵ��false:����Ϊ��ֵ 
    }
	
	@RequestMapping(value = "/listInterface")
	@ResponseBody
	public ModelAndView listInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Content/list.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
			
	/**
	 *  <!--角色列表 分页     -->
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/list", method = RequestMethod.POST) 
	@ResponseBody
	public Map<String, Object>  Userlist(@RequestParam Map<String, Object> data,  SiteContent siteContent, HttpServletRequest request,
			HttpServletResponse response) throws Exception{		
		Map<String, Object> result = new HashMap<String, Object>();		
		data.put("isModule", "1");//内容 模块列表
		data.put("is_deleted", "0");
		PageInfo<SiteContent> page = SiteContentService.list(data);
		result.put("total", page.getTotal());
		result.put("rows", page.getList());
		return result;	
	}
	
	/**
	 * 查询所有数据,
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/queryAll")
	@ResponseBody
	public List<SiteContent> queryTCityAQIWriteAll(@RequestParam Map<String, Object> data,
			HttpServletRequest request,	HttpServletResponse response) throws Exception{
		
		data.put("is_deleted", "0");		
		List<SiteContent>  SiteContent= SiteContentService.queryAll(data);
		return SiteContent;
	}
	
	/**
	 * 点击添加跳转到增加界面
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/addInterface")
	@ResponseBody
	public ModelAndView addInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Content/edit.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}	
	
	@Autowired //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private SiteMenuService  siteMenuService; 
	
	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/save")
	@ResponseBody	
	public Map<String,Object> save(@RequestParam Map<String, Object> data,
			SiteContent  siteContent,SiteMenu  siteMenu, HttpServletRequest request,	HttpServletResponse response) throws Exception{		
		ModelAndView mav = new ModelAndView();
		try {	
			//是否新增 导航内容
			if(data.get("type")!=null&&data.get("type").equals("addMenu")){ //导航菜单
				//siteMenu.setCategoryID(1);//代表是内容
				// siteMenu.setUrl(data.get("tag").toString());
				int rows = siteMenuService.add(siteMenu);	
				if(rows>0){
					String url="/SiteIndex/content.htm?fk_menuId="+BaseCodec.encode(siteMenu.getId().toString().getBytes());
					siteMenu.setUrl(url);
					siteMenuService.update(siteMenu);
					
					siteContent.setFk_menuId(siteMenu.getId());					
					siteContent.setIsModule(0);
				}			
			}else{
				siteContent.setFk_menuId(null);
				siteContent.setIsModule(1); //是内容模块
			}			
			siteContent.setTitle(data.get("menuName").toString());		
			if(siteContent.getContents()!=null && !siteContent.getContents().equals(" ")){				
				siteContent.setContents(StringUtil.replaceEnter(siteContent.getContents())); // 去除换行符				
			}
			
			int exeCount = SiteContentService.add(siteContent);			
			if (exeCount > 0) {
				
				
				data.put("success", true);
			} else {
				data.put("success", false);
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}	
	

	
	/**
	 * 点击修改跳转到增加界面
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updateInterface")
	@ResponseBody
	public ModelAndView updateInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request,SiteContent  siteContent,
			HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			if(data.get("type")!=null&&data.get("type").equals("editMenu")){ //导航菜单 编辑
				SiteMenu siteMenu=new SiteMenu();
				int fk_menuId=Integer.parseInt(data.get("fk_menuId").toString());
				siteMenu.setId(fk_menuId);
				siteMenu=siteMenuService.queryById(siteMenu);		
				data.put("siteMenu", siteMenu);				
				
				siteContent = SiteContentService.queryByMenuId(siteContent);	
			}else{
				siteContent = SiteContentService.queryById(siteContent);
			}	
			if(siteContent.getContents()!=null && !siteContent.getContents().equals(" ")){				
				siteContent.setContents(StringUtil.replaceEnter(siteContent.getContents())); // 去除换行符				
			}			
			data.put("siteContent", siteContent);			
			
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Content/edit.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
		
	/**
	 * 修改信息
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> update(@RequestParam Map<String, Object> data,
			SiteContent  siteContent,SiteMenu  siteMenu, HttpServletRequest request,
			HttpServletResponse response) {
		try {		
			if(data.get("type")!=null&&data.get("type").equals("editMenu")){ //导航菜单  修改
				int fk_menuId=Integer.parseInt(data.get("fk_menuId").toString());
				siteMenu.setId(fk_menuId);
				siteMenu.setUrl(data.get("tag").toString());
				int rows = siteMenuService.update(siteMenu);	
				if(rows>0){
					siteContent.setFk_menuId(siteMenu.getId());					
					siteContent.setIsModule(0);
				}								
			}else{
				siteContent.setFk_menuId(null);
				siteContent.setIsModule(1); //是内容模块
			}				
			siteContent.setTitle(data.get("menuName").toString());			
			int exeCount = SiteContentService.update(siteContent);			
			if (exeCount > 0) {
				data.put("success", true);
			} else {
				data.put("success", false);
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}
	
	
	/**
	 * 删除信息
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(@RequestParam Map<String, Object> data,
			HttpServletRequest request,	HttpServletResponse response) {
		try {			
			String[] idArr=data.get("ids").toString().split(",");
			for(String id:idArr){
				int exeCount=0;
				if(data.get("type")!=null&&data.get("type").equals("deleMenu")){ //导航菜单  修改
					//先删除 Menu
					SiteMenu  siteMenu=new SiteMenu();
					siteMenu.setId(Integer.parseInt(id));											
					exeCount=siteMenuService.delete(siteMenu);
					if(exeCount>0){
						//根据 fk_menu删除content				
						SiteContent  siteContent=new SiteContent();
						siteContent.setFk_menuId(siteMenu.getId());											
						exeCount=SiteContentService.deleteByMenu(siteContent);
					}					
				}else{
					SiteContent  siteContent=new SiteContent();
					siteContent.setId(Integer.parseInt(id));											
					exeCount=SiteContentService.delete(siteContent);
				}
				if (exeCount > 0) {
					data.put("success", true);
				} else {
					data.put("success", false);
				}
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}
	
}
